-- GameCar
module(..., package.seeall)

local shape1;
local gameGroup;

function newCar(game,hud,endLevel)
	
	--[[
	shape1 = display.newImage( "shape3.png" , { friction=0.6, density = 0.1 })
	shape1.x = 110; shape1.y = 380
	
	]]--
	
	gameGroup = game;
	
	shape1 = display.newImage( "shape3.png" , { friction=0.6, density = 0.1 })
	shape1.x = 20; shape1.y = 280;
	
	physics.addBody( shape1, { friction=0.6})
	game:insert(shape1);
	
	barra1 = display.newImage( "barra.png", { friction=0.6, density = 0.1})
	barra1.x = shape1.x - 45;
	barra1.y = shape1.y - 30;
	physics.addBody(barra1);
	game:insert(barra1);
	
	barra2 = display.newImage( "barra.png", { friction=0.6, density = 0.1 })
	barra2.x = shape1.x + 45;
	barra2.y = shape1.y - 30;
	physics.addBody(barra2);
	game:insert(barra2);
	
	wheel1 = display.newImage( "ball2.png" )
	wheel1.x = shape1.x + 40; wheel1.y = 300
	physics.addBody( wheel1, { friction=0.6, radius=15, density = 0.5 } )
	wheel1.Xscale = 1.50;
	wheel1.Yscale = 1.50;
	game:insert(wheel1);

	wheel2 = display.newImage( "ball2.png" )
	wheel2.x = shape1.x-50; wheel2.y = 300
	physics.addBody( wheel2, { friction=0.6, radius=15,density = 0.5 } )
	wheel2.Xscale = 1.50;
	wheel2.Yscale = 1.50;
	game:insert(wheel2);


	carga1 = display.newImage("boulder.png");
	carga1.x = shape1.x + 15;
	carga1.y = shape1.y - 30;
	physics.addBody( carga1, { friction=0.8, radius=20,density = 0.007, bounce = 0} )
	game:insert(carga1);
	
	carga2 = display.newImage("egg.png");
	carga2.x = shape1.x - 15;
	carga2.y = shape1.y - 30;
	physics.addBody( carga2, { friction=1, radius=10,density = 0.01, bounce = 0.5} )
	game:insert(carga2);
	
	physics.newJoint( "pivot", wheel1, shape1, wheel1.x, wheel1.y)
	physics.newJoint( "pivot", wheel2, shape1, wheel2.x, wheel2.y)
	
	physics.newJoint( "weld", shape1, barra1, shape1.x - 45, shape1.y - 30)
	physics.newJoint( "weld", shape1, barra2, shape1.x + 45, shape1.y - 30)
	
	local function moveCamera()
		
		if (shape1.x ~= nil) then
		
			if (shape1.x > 80 and shape1.x < 1100) then
				game.x = - shape1.x + 80;
				hud.x = shape1.x - 80;
			elseif (shape1.x >= 1300) then
				print("Remove Listener");
				shape1:removeEventListener( "enterFrame", moveCamera );
				endLevel();
			end
		end
	end

	
	shape1:addEventListener("touch", onTouch);
	Runtime:addEventListener( "enterFrame", moveCamera );
	
end

function onTouch(event)		
	print("car touched");
	if (event.phase == "began") then
		shape1:applyForce( 70, 0, shape1.x, shape1.y )
	end	
	return true;
end